//
//  LZFPlaceholderTextView.m
//  LZFPlaceholderTextView
//
//  Created by 梁梓烽 on 16/7/7.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "LZFPlaceholderTextView.h"

@implementation LZFPlaceholderTextView

-(instancetype)initWithFrame:(CGRect)frame

{
    if (self=[super initWithFrame:frame]) {
        
        //设置默认的颜色和字体和占位文字
        self.textColor=[UIColor grayColor];
        self.font=[UIFont systemFontOfSize:17];
        self.placeHolder=@"默认的占位文字...";
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
        
    }
    
    return self;
}


-(void)textDidChange:(NSNotification *)notice
{
    [self setNeedsDisplay];
}

//系统在view显示之前会调用一次,每次调用drawRect之前,都会把之前的东西清掉
-(void)drawRect:(CGRect)rect
{
    //有字体的画就返回
    if (self.hasText) return;
    
    //只要判断没有文字,就用新的颜色和字体在指定的rect画占位文字出来
    NSMutableDictionary *dic =[NSMutableDictionary new];
    dic[NSFontAttributeName]=self.font;
    dic[NSForegroundColorAttributeName]=self.placeHodlerColor;
    rect.origin.x=5;
    rect.origin.y=8;
    rect.size.width=[UIScreen mainScreen].bounds.size.width-2*rect.origin.x;
    
    [self.placeHolder drawInRect:rect withAttributes:dic];
}


#pragma mark 容错处理,外界手动设置占位文字的颜色和字体时,重新调用drawRect方法
-(void)setPlaceHodlerColor:(UIColor *)placeHodlerColor
{
    _placeHodlerColor=placeHodlerColor;
    [self setNeedsDisplay];
}


-(void)setFont:(UIFont *)font
{
    [super setFont:font];
    [self setNeedsDisplay];
}


-(void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    [self setNeedsDisplay];
}



-(void)setText:(NSString *)text
{
    [self setText:text];
    [self setNeedsDisplay];
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    [self setNeedsDisplay];
}


@end
